package com.api.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

/**
 * @author 李大牛家的牛 (scafel@163.com)
 * @createDate 2025/5/20-15:13
 * @description ToDo...
 **/
public class NetWorkUtils {

    // 定义常量，避免硬编码
    private static final String HEADER_X_FORWARDED_FOR = "x-forwarded-for";
    private static final String HEADER_PROXY_CLIENT_IP = "Proxy-Client-IP";
    private static final String HEADER_WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";
    private static final String UNKNOWN_IP = "unknown";
    private static final String LOCALHOST_IP = "127.0.0.1";

    // 正则表达式用于校验 IP 地址合法性
    private static final Pattern IPV4_PATTERN = Pattern.compile(
            "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$"
    );

    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return null;
        }

        String ip = extractIpFromHeader(request, HEADER_X_FORWARDED_FOR);

        if (isInvalidIp(ip)) {
            ip = extractIpFromHeader(request, HEADER_PROXY_CLIENT_IP);
        }

        if (isInvalidIp(ip)) {
            ip = extractIpFromHeader(request, HEADER_WL_PROXY_CLIENT_IP);
        }

        if (isInvalidIp(ip)) {
            ip = request.getRemoteAddr();
            if (LOCALHOST_IP.equals(ip)) {
                ip = getLocalhostIp();
            }
        }

        // 处理多个代理的情况
        if (ip != null && ip.length() > 15 && ip.contains(",")) {
            ip = ip.split(",")[0].trim(); // 获取第一个 IP 并去除空格
        }

        // 校验 IP 合法性
        if (!isValidIp(ip)) {
            return null; // 如果 IP 不合法，返回 null
        }

        return ip;
    }

    // 提取 IP 的公共方法
    private static String extractIpFromHeader(HttpServletRequest request, String headerName) {
        String ip = request.getHeader(headerName);
        return isInvalidIp(ip) ? null : ip;
    }

    // 判断 IP 是否无效
    private static boolean isInvalidIp(String ip) {
        return ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip);
    }

    // 获取本地主机 IP
    private static String getLocalhostIp() {
        try {
            InetAddress inet = InetAddress.getLocalHost();
            return inet.getHostAddress();
        } catch (UnknownHostException e) {
            // 异常处理，返回默认值
            return LOCALHOST_IP;
        }
    }

    // 校验 IP 合法性
    private static boolean isValidIp(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }
        return IPV4_PATTERN.matcher(ip).matches();
    }

    public static String getOsName(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String userAgentHeader = request.getHeader("user-agent");
        return getOsNameByHeader(userAgentHeader);
    }

    private static String getOsNameByHeader(String userAgentHeader) {
        if (userAgentHeader == null) {
            return null;
        }
        // 如果User-Agent字符串长度超过200个字符，则截取前200个字符
        if (userAgentHeader.length() > 200) {
            // 在截取的字符串末尾添加省略号，表明被截断了
            return userAgentHeader.substring(0, 200) + "...";
        } else {
            return userAgentHeader;
        }
    }
}
